// Server API makes it possible to hook into various parts of Gridsome
// on server-side and add custom data to the GraphQL data layer.
// Learn more: https://gridsome.org/docs/server-api/

// Changes here require a server restart.
// To restart press CTRL + C in terminal and run `gridsome develop`


const axios = require('axios')

module.exports = function (api) {
  const token = '27fa4b905a7907119b2ae80c9cf1a67a893107fc';

  api.loadSource(async ({ addCollection }) => {
    const collection = addCollection('Gist')
    const { data } = await axios.get(`https://api.github.com/users/Super-pig/gists?page=1&per_page=1&access_token=${token}`)

    if (!data || data.length == 0) {
      return
    }

    const { data: result } = await axios.get(`${data[0].url}?access_token=${token}`)

    for (let key in result.files) {
      collection.addNode({
        title: key,
        content: result.files[key]['content'],
        description: result['description'],
        createTime: result['created_at'],
        updateTime: result['updated_at']
      })
    }
  })

  api.createPages(({ createPage }) => {
    // Use the Pages API here: https://gridsome.org/docs/pages-api/
  })
}
